package com.tangsm.spring.boot.springdoc.controller;

import com.tangsm.spring.boot.springdoc.exception.BusinessException;
import com.tangsm.spring.boot.springdoc.api.UserApi;
import com.tangsm.spring.boot.springdoc.domain.base.Result;
import com.tangsm.spring.boot.springdoc.domain.dto.User;
import com.tangsm.spring.boot.springdoc.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户管理
 *
 * @author tangsm
 * @date 2021-07-27 16:33:01
 */
@RequestMapping("/user")
@RestController
public class UserController implements UserApi {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    @GetMapping(value = "/list")
    @Override
    public Result<List<User>> listAll() {
        return Result.success(userService.listAll());
    }

    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    @GetMapping("/getById/{id}")
    @Override
    public Result<User> getById(@PathVariable(value = "id") Long id) {
        log.debug("id = {}", id);
        return Result.success(userService.getById(id));
    }

    /**
     * 新增，忽略null字段
     *
     * @param user 新增的记录
     * @return 返回影响行数
     */
    @PostMapping("/insert")
    @Override
    public Result<Integer> insert(@Valid @RequestBody User user) throws BusinessException {
        return Result.success(userService.insertIgnoreNull(user));
    }

    /**
     * 修改，忽略null字段
     *
     * @param user 修改的记录
     * @return 返回影响行数
     */
    @PutMapping("/update")
    @Override
    public Result<Integer> update(@RequestBody User user) {
        return Result.success(userService.updateIgnoreNull(user));
    }

    /**
     * 删除记录
     *
     * @param id 待删除的记录
     * @return 返回影响行数
     */
    @DeleteMapping("/delete/{id}")
    @Override
    public Result<Integer> delete(@PathVariable(value = "id") Long id) {
        return Result.success(userService.delete(id));
    }
}
